package com.gitee.qdbp.jdbc.result;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.LinkedHashMap;
import java.util.Map;
import org.springframework.jdbc.support.JdbcUtils;
import com.gitee.qdbp.jdbc.plugins.DbPluginHelper;
import com.gitee.qdbp.jdbc.plugins.TablesFieldColumnParser;

/**
 * Row转换为Map<br>
 * 如果存在同名字段, 以先出现的为准, 忽略后出现的
 *
 * @author zhaohuihua
 * @version 20201109
 */
public class SimpleRowToMapMapper implements RowToMapMapper, DbPluginHelper.Aware {

    /** 插件容器 **/
    protected DbPluginHelper plugins;

    @Override
    public void setPlugins(DbPluginHelper plugins) {
        this.plugins = plugins;
    }

    @Override
    public Map<String, Object> mapRow(ResultSet rs, int rowNum) throws SQLException {
        ResultSetMetaData rsmd = rs.getMetaData();
        int columnCount = rsmd.getColumnCount();
        Map<String, Object> mapOfColumnValues = new LinkedHashMap<>(columnCount);
        for (int i = 1; i <= columnCount; i++) {
            String fieldName = getFieldName(JdbcUtils.lookupColumnName(rsmd, i));
            if (mapOfColumnValues.containsKey(fieldName)) {
                continue;
            }
            Object object = getColumnValue(rs, i);
            mapOfColumnValues.put(fieldName, object);
        }
        return mapOfColumnValues;
    }

    protected String getFieldName(String columnName) {
        TablesFieldColumnParser parser = plugins.getTablesFieldColumnParser();
        // 表别名与列别名的分隔符
        String tableAliasSeparator = parser.getTableAliasSeparator();
        int tableAliasIndex = columnName.indexOf(tableAliasSeparator);
        if (tableAliasIndex >= 0) {
            columnName = columnName.substring(tableAliasIndex + tableAliasSeparator.length());
        }
        return columnNameToFieldName(columnName);
    }

    protected String columnNameToFieldName(String columnName) {
        return columnName;
    }

    protected Object getColumnValue(ResultSet rs, int index) throws SQLException {
        return JdbcUtils.getResultSetValue(rs, index);
    }
}
